﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using AISservice.Common;
using Common;
using Microsoft.AspNetCore.Mvc;

namespace AISservice.Controllers
{
    [Route("api/v1/[controller]/[action]")]
    [ApiController]
    public class MethodController : ControllerBase
    {
        

        [HttpGet]
        public ActionResult<string> GetServerDate()
        {
            return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }

        [HttpPost]
        public ActionResult<MQResponse> DealException(dynamic request)
        {
  
            MQResponse execresult = new MQResponse() { ResponseCode = "200" };
            string req = request.ToString();
            execresult.ResponseCode = CommonHandler.GetException(req, "CODE", "500").ToString();
            execresult.Message = CommonHandler.GetException(req, "DESC", req).ToString();
            if (string.IsNullOrWhiteSpace(execresult.Message))
            {
                execresult.Message = CommonHandler.GetException(req, "TITLE", req).ToString();
            }
            int errline = CommonHandler.GetErrorControlLine(req);
            if (errline >= 0)
                execresult.Message += System.Environment.NewLine + $"第{errline}行";

            
            return execresult;
        }



        [HttpGet]
        public ActionResult<string> GetF6()
        {
            return JsonHelper.ObjectToJson( new BLL.orderHandler().GetF6Order("4D0D0F2A-905B-480B-8F89-59EA75F09827"));
        }

        private  object ExecuteMethod(String controler, string action, params object[] param)
        {
           
            if (RoutingService.Method_List.ContainsKey(controler + "." + action))
            {

                var method = (RoutingService.Method_List[controler + "." + action].First as MethodInfo);
                //foreach (object obj in param)
                //{
                //    Console.WriteLine(DateTime.Now.ToLongTimeString() + "  Param:" + obj);
                //    System.Diagnostics.Debugger.Log(0, null, string.Format("队列{0}处理请求参数{1}", Properties.Settings.Default.MQQueue
                //                 , obj==null ?"":  obj.ToString()));
                //}
                return JsonHelper.ObjectToJson(method.Invoke(RoutingService.Method_List[controler + "." + action].Second, param));  //Newtonsoft.Json.JsonConvert.SerializeObject(method.Invoke(ObjCache[controler], param));
            }
            return "";


        }
        /// <summary>
        /// 传JSON格式的请求。暂时保留此方法
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult<string> Invoke(MQRequest req)
        {
            string execresult = string.Empty;
            if (RoutingService.Method_List.ContainsKey(req.Controller + "." + req.Action))
            {
                object[] Objparams = DealParam(req.Controller, req.Action, req.MessageBody);    //JsonHelper.JsonToObject<object[]>(request.MessageBody);   //JsonConvert.DeserializeObject<Object[]>(request.MessageBody);
                execresult = ExecuteMethod(req.Controller, req.Action, Objparams).ToString();
            }
            return execresult;
        }

        private  object[] DealParam(String controler, string anction, string strparam)
        {
            //todo:这里建议不要在参数最外面增加多"，而是传入实体对象的数组
            List<object> objparam = new List<object>();
            Dictionary<string, object> pairs = null;
            if (anction.Equals("Update"))
            {
                pairs = new Dictionary<string, object>();
                List<string> vs = new List<string>();
                foreach (string entry in JsonHelper.JsonToObject<List<string>>(strparam))
                {
                    vs.Add(entry);
                }
                pairs.Add("objlist", vs.ToArray());
            }
            else if (anction.Equals("SaveView"))
            {
                pairs = new Dictionary<string, object>();
                List<string> vs = new List<string>();
                foreach (string entry in JsonHelper.JsonToObject<List<string>>(strparam))
                {
                    vs.Add(entry);
                }
                pairs.Add("objlist", vs.ToArray());
            }
            else
                pairs = JsonHelper.JsonToObject<Dictionary<string, object>>(strparam);

            MethodInfo method = (RoutingService.Method_List[controler + "." + anction].First as MethodInfo);
            if (method != null)
            {
                ParameterInfo[] parameters = method.GetParameters();
                foreach (ParameterInfo info in parameters)
                {
                    if (pairs.ContainsKey(info.Name))
                    {
                        Object value = pairs[info.Name];

                        if (info.ParameterType == typeof(Int32))
                        {
                            value = Convert.ToInt16(value);
                        }
                        objparam.Add(value);
                    }
                    else
                    {
                        objparam.Add(null);
                    }

                }
            }

            return objparam.ToArray();

        }







       
    }
}
